// 删除未使用的导入

// 地图操作控制器
//import goFishingIcon from '../assets/images/go-fishing.png'

// 声明qq对象的类型
declare global {
  interface Window {
    qq: any;
  }
}

export interface MapHandler {
  display(): void
  auto(): Boolean
  setData(data: any): void
  name: string
  type: string
  description?: string
  active: boolean
  activate(): void
  deactivate(): void
  onComplete?: (data: any) => void
}

export abstract class BaseMapHandler implements MapHandler {
  name: string
  type: string
  description?: string
  active: boolean
  data: any = null
  constructor() {
    this.name = ''
    this.type = ''
    this.description = ''
    this.active = false
  }
  display(): void {
    if (this.auto()) {
      this.activate()
    }
  }
  auto(): Boolean {
    return false

  }
  setData(data: any): void {
    this.data = data
  }
  activate(): void {
    this.active = true
  }
  deactivate(): void {
    this.active = false
    this.data = null
  }

  createMarker(map: any, point: { lat: number, lng: number }, title: string) {
    const qq = (window as any).qq;
    if (!qq || !qq.maps || !map || !point?.lat || !point?.lng) {
      console.error('创建标记失败：缺少必要参数或腾讯地图API未加载');
      return null;
    }
    
    const marker = new qq.maps.Marker({
      position: new qq.maps.LatLng(point.lat, point.lng),
      map: map,
      title: title,
      icon: {
       // url: goFishingIcon,
        size: new qq.maps.Size(25, 40),
        anchor: new qq.maps.Point(12.5, 40)
      }
    });
    return marker;
  }

  createInfoWindow(
    map: any,
    point: { lat: number; lng: number },
    title: string,
    style?: {
      bgColor?: string;    // 背景色
      padding?: string;    // 内边距
      fontSize?: string;   // 字体大小
      maxWidth?: string;   // 最大宽度（避免内容过长）
    }
  ) {
    const qq = (window as any).qq;
    if (!qq || !qq.maps || !map || !point?.lat || !point?.lng || !title) {
      console.error('创建信息窗口失败：缺少必要参数或腾讯地图API未加载');
      return null;
    }

    const defaultStyle = {
      bgColor: '#fff',
      padding: '6px 1px',
      fontSize: '14px',
      maxWidth: '200px',
      borderRadius: '4px',
      boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
      color: '#333'
    };
    const finalStyle = { ...defaultStyle, ...style };

    const content = `
    <div class="info-window1" style="
      background: ${finalStyle.bgColor};
      padding: ${finalStyle.padding};
      font-size: ${finalStyle.fontSize};
      max-width: ${finalStyle.maxWidth};
      border-radius: ${finalStyle.borderRadius};
      box-shadow: ${finalStyle.boxShadow};
      color: ${finalStyle.color};
      white-space: normal;
    ">
      ${title}
    </div>
  `;

    const infoWindow = new qq.maps.InfoWindow({
      position: new qq.maps.LatLng(point.lat, point.lng),
      content: content,
      map: map,
      disableAutoPan: false,
      visible: true,
      showClose: false
    });

    qq.maps.event.addListener(map, 'click', () => {
      if (infoWindow) {
        infoWindow.open(map);
      }
    });

    qq.maps.event.addListener(map, 'dblclick', () => {
      if (infoWindow) {
        infoWindow.open(map);
      }
    });

    return infoWindow;
  }

  createLabel(map: any,
    point: { lat: number; lng: number },
    title: string) {
    const qq = (window as any).qq
    try {
      return new qq.maps.Label({
        position: new qq.maps.LatLng(point.lat, point.lng),
        content: title,
        map: map,
        offset: new qq.maps.Size(20, 30),
        style: {
          color: "#3777FF", // 文字颜色
          fontSize: "16px", // 字体大小
          fontWeight: "bold", // 字体加粗
          padding: "2px 8px", // 内边距（避免文字过挤）
          whiteSpace: "nowrap", // 文本不换行（默认）
          border: "1px solid #3777FF", // 无边框
          borderRadius: "4px",
          margin: "10px 0 0 0 ",
          cursor: 'grab'
        }
      });
    } catch (error) {
      console.error('创建标签失败：', error);
    }
  }

  createPolygon(map: any, points: Array<{ lat: number; lng: number }>) {
    const qq = (window as any).qq
    const path = points.map(p => new qq.maps.LatLng(p.lat, p.lng))
    return new qq.maps.Polygon({
      path: path,
      strokeColor: '#FF0000',
      strokeWeight: 3,
      map: map
    })
  }

  createPolyline(map: any, points: Array<{ lat: number; lng: number }>) {
    const qq = (window as any).qq
    const path = points.map(p => new qq.maps.LatLng(p.lat, p.lng))
    return new qq.maps.Polyline({
      path: path,
      strokeColor: '#FF0000',
      strokeWeight: 3,
      map: map
    })
  }
}

export class PickupPointHandler extends BaseMapHandler {
  name = '取点'
  type = 'pickup-point'
  description = '在地图上选择点'
  active = false
  data: any = null

  // @ts-expect-error 预留的回调函数，将在未来的功能扩展中使用
  constructor(private _onPointSelect: (point: { lat: number; lng: number }) => void) {
    super()
  }

  onComplete?: ((data: any) => void) | undefined

  activate(): void {
    this.active = true
    console.log('取点模式已激活')
    // 这里可以添加地图点击监听
  }

  deactivate(): void {
    this.active = false
    console.log('取点模式已停用')
  }
}

export class DrawLineHandler extends BaseMapHandler {
  name = '画线'
  type = 'draw-line'
  description = '绘制路线或边界'
  active = false

  // @ts-expect-error 预留的回调函数，将在未来的功能扩展中使用
  constructor(private _onLineComplete: (points: Array<{ lat: number; lng: number }>) => void) {
    super()
  }
  setData(_data: any): void {
    throw new Error("Method not implemented.")
  }
  onComplete?: ((data: any) => void) | undefined

  activate(): void {
    this.active = true
    console.log('画线模式已激活')
  }

  deactivate(): void {
    this.active = false
    console.log('画线模式已停用')
  }
}

export class MeasureHandler extends BaseMapHandler {
  name = '测量'
  type = 'measure'
  description = '测量距离'
  active = false

  // @ts-expect-error 预留的回调函数，将在未来的功能扩展中使用
  constructor(private _onMeasureComplete: (distance: number) => void) {
    super()
  }

  activate(): void {
    this.active = true
    console.log('测量模式已激活')
  }

  deactivate(): void {
    this.active = false
    console.log('测量模式已停用')
  }
}

export class MarkHandler extends BaseMapHandler {
  name = '标记'
  type = 'mark'
  description = '添加地图标记'
  active = false

  // @ts-expect-error 预留的回调函数，将在未来的功能扩展中使用
  constructor(private _onMarkComplete: (mark: { lat: number; lng: number; label: string }) => void) {
    super()
  }

  activate(): void {
    this.active = true
    console.log('标记模式已激活')
  }

  deactivate(): void {
    this.active = false
    console.log('标记模式已停用')
  }
}

export class AreaHandler extends BaseMapHandler {
  name = '面积'
  type = 'area'
  description = '计算区域面积'
  active = false

  // @ts-expect-error 预留的回调函数，将在未来的功能扩展中使用
  constructor(private _onAreaComplete: (area: number) => void) {
    super()
  }

  activate(): void {
    this.active = true
    console.log('面积计算已激活')
  }

  deactivate(): void {
    this.active = false
    console.log('面积计算已停用')
  }
}

export class PolygonDrawHandler extends BaseMapHandler {
  name = '绘制多边形'
  type = 'polygon-draw'
  description = '绘制无交叉多边形'
  active = false

  private points: Array<{ lat: number, lng: number }> = []
  private markers: any[] = []
  private polyline: any = null
  private polygon: any = null
  private clickListener: any = null
  private rightClickListener: any = null

  constructor(private onPolygonComplete: (points: Array<{ lat: number, lng: number }>) => void) {
    super()
  }

  activate(): void {
    this.active = true
    this.setupEventListeners()
    console.log('多边形绘制已激活')
  }

  deactivate(): void {
    this.active = false
    this.cleanup()
    console.log('多边形绘制已停用')
  }

  handle(): void {
    // 处理器激活时开始绘制模式
    console.log('多边形绘制模式已启动')
  }

  private setupEventListeners(): void {
    if (!this.active) {
      console.log('PolygonDrawHandler: 未激活，跳过事件设置')
      return
    }

    const map = mapController.getMap()
    if (!map) {
      console.warn('PolygonDrawHandler: 地图实例为null')
      return
    }

    const qq = (window as any).qq


    try {
      // 直接绑定click事件到地图实例
      this.clickListener = qq.maps.event.addListener(map, 'click', (event: any) => {
        const lat = event.latLng.lat
        const lng = event.latLng.lng
        this.handleMapClick({ latLng: { lat, lng } })
      })

      this.rightClickListener = qq.maps.event.addListener(map, 'rightclick', (_event: any) => {
        this.completePolygon()
      })


    } catch (error) {
      console.error('PolygonDrawHandler: 设置事件监听器失败', error)
    }
  }

  private handleMapClick(event: any): void {
    if (!this.active) return

    const lat = event.latLng.lat
    const lng = event.latLng.lng
    const point = { lat, lng }

    if (!this.canAddPoint(point)) {
      console.log('无法添加点：会导致线段交叉')
      return
    }

    this.addPoint(point)
  }

  private canAddPoint(newPoint: { lat: number, lng: number }): boolean {
    if (this.points.length < 2) return true

    const testPoints = [...this.points, newPoint]

    // 检查线段交叉
    if (this.hasCrossingSegments(testPoints)) {
      return false
    }

    // 检查闭合线段是否会交叉
    if (testPoints.length >= 3 && this.hasClosingCrossing(testPoints)) {
      return false
    }

    return true
  }

  private addPoint(point: { lat: number, lng: number }): void {
    this.points.push(point)
    this.addMarker(point)
    this.updatePolyline()

    console.log(`已添加点 ${this.points.length}: ${point.lat}, ${point.lng}`)

    if (this.points.length === 3) {
      console.log('已选择3个点，右键点击地图任意位置完成多边形')
    } else if (this.points.length > 3) {
      console.log(`已选择${this.points.length}个点，右键点击地图任意位置完成多边形`)
    }
  }

  private addMarker(point: { lat: number, lng: number }): void {
    const map = mapController.getMap()
    if (!map) return

    const marker = this.createMarker(map, point, `点 ${this.markers.length}`)
    this.markers.push(marker)
  }

  private updatePolyline(): void {
    const map = mapController.getMap()
    if (!map) return

    if (this.polyline) {
      this.polyline.setMap(null)
    }

    if (this.points.length > 1) {
      this.polyline = this.createPolyline(map, this.points)
    }
  }



  private completePolygon(): void {
    if (this.points.length < 3) {
      console.log('需要至少3个点才能形成多边形')
      return
    }

    if (this.hasCrossingSegments(this.points)) {
      console.log('多边形无效：存在线段交叉')
      return
    }

    this.drawPolygon()
    console.log('多边形绘制完成！顶点坐标：', this.points)

    // 触发多边形编辑事件
    this.onPolygonComplete(this.points)

    this.cleanup()
  }

  private drawPolygon(): void {
    const map = mapController.getMap()
    if (!map || this.points.length < 3) return

    if (this.polyline) {
      this.polyline.setMap(null)
    }

    this.polygon = this.createPolygon(map, this.points)

  }

  private hasCrossingSegments(points: Array<{ lat: number, lng: number }>): boolean {
    if (points.length < 3) return false

    // 检查所有非相邻线段是否交叉as
    for (let i = 0; i < points.length - 2; i++) {
      for (let j = i + 2; j < points.length - 1; j++) {
        if (this.doSegmentsIntersect(points[i], points[i + 1], points[j], points[j + 1])) {
          return true
        }
      }
    }

    return false
  }

  private hasClosingCrossing(points: Array<{ lat: number, lng: number }>): boolean {
    if (points.length < 3) return false

    const lastPoint = points[points.length - 1]
    const firstPoint = points[0]

    // 只检查闭合线段与非相邻的中间线段是否交叉
    // 跳过相邻的线段（点1->点2和点n-1->点n）
    for (let i = 1; i < points.length - 2; i++) {
      if (this.doSegmentsIntersect(lastPoint, firstPoint, points[i], points[i + 1])) {
        return true
      }
    }

    return false
  }

  private doSegmentsIntersect(p1: { lat: number, lng: number }, p2: { lat: number, lng: number },
    p3: { lat: number, lng: number }, p4: { lat: number, lng: number }): boolean {
    const det = (a: number, b: number, c: number, d: number) => a * d - b * c

    const x1 = p1.lng, y1 = p1.lat
    const x2 = p2.lng, y2 = p2.lat
    const x3 = p3.lng, y3 = p3.lat
    const x4 = p4.lng, y4 = p4.lat

    const denom = det(x1 - x2, y1 - y2, x3 - x4, y3 - y4)
    if (Math.abs(denom) < 1e-10) return false

    const t = det(x1 - x3, y1 - y3, x3 - x4, y3 - y4) / denom
    const u = det(x1 - x2, y1 - y2, x1 - x3, y1 - y3) / denom

    return t >= 0 && t <= 1 && u >= 0 && u <= 1
  }

  private cleanup(): void {

    if (this.clickListener) {
      const qq = (window as any).qq
      qq.maps.event.removeListener(this.clickListener)
      this.clickListener = null

    }

    if (this.rightClickListener) {
      const qq = (window as any).qq
      qq.maps.event.removeListener(this.rightClickListener)
      this.rightClickListener = null

    }

    this.markers.forEach(marker => marker.setMap(null))
    this.markers = []

    if (this.polyline) {
      this.polyline.setMap(null)
      this.polyline = null
    }

    if (this.polygon) {
      this.polygon.setMap(null)
      this.polygon = null
    }

    this.points = []

  }
}

// 移动到当前位置处理器
export class MoveToCurrentPositionHandler extends BaseMapHandler {
  name = '移动到当前位置'
  type = 'move-to-current'
  description = '移动地图到当前位置'
  active = false

  constructor(private map: any) {
    super()
  }

  activate(): void {
    this.active = true
    this.moveToCurrentPosition()
    // 执行后立即停用，因为这是单次操作
    setTimeout(() => {
      this.deactivate()
    }, 100)
  }

  deactivate(): void {
    this.active = false
  }

  private moveToCurrentPosition(): void {
    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const userLat = position.coords.latitude
          const userLng = position.coords.longitude

          if (this.map) {
            const qq = (window as any).qq
            const userLocation = new qq.maps.LatLng(userLat, userLng)
            this.map.setCenter(userLocation)
            this.map.setZoom(15)

            // 添加当前位置标记
            this.addCurrentPositionMarker(userLocation)
          }
        },
        (error) => {
          console.warn('获取位置失败:', error.message)
        },
        {
          enableHighAccuracy: true,
          timeout: 5000,
          maximumAge: 300000
        }
      )
    } else {
    }
  }

  private addCurrentPositionMarker(location: any): void {
    if (this.map) {
      const qq = (window as any).qq

      // 移除之前的位置标记
      if ((window as any).currentPositionMarker) {
        (window as any).currentPositionMarker.setMap(null)
      }

      // 添加新的位置标记
      const marker = new qq.maps.Marker({
        position: location,
        map: this.map,
        title: '当前位置',
        icon: new qq.maps.MarkerImage(
          'data:image/svg+xml;base64,' + btoa(`
            <svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <circle cx="12" cy="12" r="8" fill="#1ed760" stroke="white" stroke-width="2"/>
              <circle cx="12" cy="12" r="3" fill="white"/>
            </svg>
          `),
          new qq.maps.Size(24, 24),
          new qq.maps.Point(0, 0),
          new qq.maps.Point(12, 12)
        )
      })

        ; (window as any).currentPositionMarker = marker
    }
  }
}

// 地图类型切换处理器
export class MapTypeSwitchHandler extends BaseMapHandler {
  name = '切换地图类型'
  type = 'map-type-switch'
  description = '在普通地图、纯卫星地图和带标注卫星地图之间循环切换'
  active = false
  private currentState: 'normal' | 'satellite' | 'hybrid' = 'normal'

  constructor(private map: any) {
    super()
  }

  activate(): void {
    this.active = true
    this.switchMapType()
    // 执行后立即停用，因为这是单次操作
    setTimeout(() => {
      this.deactivate()
    }, 100)
  }

  deactivate(): void {
    this.active = false
  }

  private switchMapType(): void {
    if (this.map) {
      const qq = (window as any).qq

      // 循环切换：normal -> satellite -> hybrid -> normal
      switch (this.currentState) {
        case 'normal':
          this.map.setMapTypeId(qq.maps.MapTypeId.SATELLITE)
          this.currentState = 'satellite'
          break

        case 'satellite':
          // 从纯卫星地图切换到带标注的卫星地图
          this.map.setMapTypeId(qq.maps.MapTypeId.HYBRID)
          this.currentState = 'hybrid'
          break

        case 'hybrid':
          // 从带标注卫星地图切换回普通地图
          this.map.setMapTypeId(qq.maps.MapTypeId.ROADMAP)
          this.currentState = 'normal'
          break
      }
    }
  }

  getCurrentMapType(): 'normal' | 'satellite' | 'hybrid' {
    return this.currentState
  }
}

export class MapSwitchHandler extends BaseMapHandler {
  name = '切换到卡片模式'
  type = 'switch-to-card-mode'
  description = '从地图模式切换回卡片模式显示'
  active = false

  constructor(private callback: () => void) {
    super()
  }

  activate(): void {
    this.active = false
    this.triggerSwitch()
  }

  deactivate(): void {
    this.active = false
  }

  triggerSwitch(): void {
    this.callback()
  }
}

export class SpotDetailHandler extends BaseMapHandler {
  name = '切换到钓点详情模式'
  type = 'switch-to-spot-detail-mode'
  description = '从地图模式切换到钓点详情模式'
  active = false
  centerMarker: any = null
  centerMakerLabel: any = null
  constructor() {
    super()
  }
  auto(): Boolean {
    return true;
  }
  activate(): void {
    this.active = true
    this.triggerDisplaySpot()
  }

  deactivate(): void {
    this.active = false
    this.centerMarker.setMap(null)
    this.centerMakerLabel.setMap(null)
  }
  triggerDisplaySpot(): void {

    const map = mapController.getMap();
    console.info(this.data)
    const point = { lat: this.data.location.latitude, lng: this.data.location.longitude };
    console.info("切换到钓点详情模式", point)
    this.centerMarker = this.createMarker(map, point, this.data.name)
    console.info("切换到钓点详情模式", this.centerMarker)
    this.centerMakerLabel = this.createLabel(map, point, this.data.name)
    console.info("切换到钓点详情模式", this.centerMakerLabel)
    const qq = (window as any).qq
    map.setCenter(new qq.maps.LatLng(point.lat, point.lng))
    setTimeout(() => {
      map.setZoom(16);
    }, 800);
  }
}
export class CircleDetailHandler extends BaseMapHandler {
  name = '钓圈详情'
  type = 'circle-detail'
  description = '显示钓圈详情'
  active = false
  polygon: any = null
  centerMarker: any = null
  centerMakerLabel: any

  constructor() {
    super()
  }
  auto(): Boolean {
    return true;
  }
  activate(): void {
    if (this.active) {
      this.deactivate
    } else {
      this.active = true
      this.displayCircleDetail()
    }
  }

  deactivate(): void {
    this.active = false
    this.polygon.setMap(null)
    this.centerMarker.setMap(null)
    this.centerMakerLabel.setMap(null)
  }
  onComplete(): void {

  }

  displayCircleDetail(): void {

    const map = mapController.getMap();
    this.polygon = this.createPolygon(map, this.data.points.map((p: { latitude: any; longitude: any }) => {
      return {
        lat: p.latitude,
        lng: p.longitude
      }
    }))
    const point = { lat: this.data.latitude, lng: this.data.longitude };

    this.centerMarker = this.createMarker(map, point, this.data.title)
    this.centerMakerLabel = this.createLabel(map, point, this.data.title)
    const qq = (window as any).qq
    map.setCenter(new qq.maps.LatLng(point.lat, point.lng))
    setTimeout(() => {
      map.setZoom(16);
    }, 800);
  }

}


// 地图控制器
export class MapController {
  private handlers: Map<string, MapHandler[]> = new Map()
  private activeMode: string | null = null
  private activeHandlers: MapHandler[] = []
  private mapInstance: any = null



  constructor() {
    // 初始化默认处理器
    this.initializeDefaultHandlers()
  }

  setMap(map: any): void {
    this.mapInstance = map
  }

  getMap(): any {
    return this.mapInstance
  }

  private initializeDefaultHandlers(): void {
    // 为yukoume注册处理器
    const yukoumeHandlers = [
      new PickupPointHandler((point) => {
        console.log('Yukoume取点:', point)
      }),
      new DrawLineHandler((points) => {
        console.log('Yukoume画线:', points)
      }),
      new MeasureHandler((distance) => {
        console.log('测量距离:', distance)
      }),
      new MarkHandler((mark) => {
        console.log('添加标记:', mark)
      }),
      new AreaHandler((area) => {
        console.log('计算面积:', area)
      })
    ]
    this.registerHandlers('yukoume', yukoumeHandlers)

    // 为fishingSpots注册处理器
    const fishingSpotsHandlers = [
      new PickupPointHandler((point) => {
        console.log('钓点取点:', point)
      }),
      new DrawLineHandler((points) => {
        console.log('钓点范围:', points)
      }),
      new MarkHandler((mark) => {
        console.log('钓点标记:', mark)
      })
    ]
    this.registerHandlers('fishingSpots', fishingSpotsHandlers)

    // 为fishingCircle注册处理器
    const fishingCircleHandlers = [
      new MapSwitchHandler(() => {
        console.log('切换到卡片模式')
        const event = new CustomEvent('toggle-map-mode', {
          detail: { isMapMode: false }
        })
        window.dispatchEvent(event)
      }),
      new PolygonDrawHandler((points) => {
        // 触发多边形完成事件用于钓点圈编辑
        const event = new CustomEvent('polygon-complete', {
          detail: { points }
        })
        window.dispatchEvent(event)
      })
    ]
    this.registerHandlers('FishingCircle', fishingCircleHandlers)


    // 为spotDetail注册处理器
    const spotDetailHandlers = [
      new MapSwitchHandler(() => {
        console.log('切换钓点详情模式')
        const event = new CustomEvent('toggle-map-mode', {
          detail: { isMapMode: false }
        })
        window.dispatchEvent(event)
      }),
      new SpotDetailHandler()
    ]
    this.registerHandlers('SpotDetail', spotDetailHandlers)

    // 为activities注册处理器
    const activitiesHandlers = [
      new PickupPointHandler((point) => {
        console.log('活动位置:', point)
      }),
      new MarkHandler((mark) => {
        console.log('活动标记:', mark)
      })
    ]
    this.registerHandlers('activities', activitiesHandlers)

    // 为profile注册处理器
    const profileHandlers = [
      new PickupPointHandler((point) => {
        console.log('个人位置:', point)
      }),
      new MarkHandler((mark) => {
        console.log('个人标记:', mark)
      })
    ]
    this.registerHandlers('profile', profileHandlers)

    this.registerHandlers('CircleDetail', [
      new MapSwitchHandler(() => {
        console.log('切换到卡片模式')
        const event = new CustomEvent('toggle-map-mode', {
          detail: { isMapMode: false, modeHandler: 'CircleDetail' }

        })
        window.dispatchEvent(event)
      }),
      new CircleDetailHandler()
    ],)

  }

  registerHandlers(mode: string, handlers: MapHandler[]): void {
    this.handlers.set(mode, handlers)
  }

  getDefaultHandlers(): MapHandler[] {
    if (!this.mapInstance) return []

    return [
      new MoveToCurrentPositionHandler(this.mapInstance),
      new MapTypeSwitchHandler(this.mapInstance)
    ]
  }

  activateMode(mode: string, data: any): void {
    console.log('MapController: 尝试激活模式', mode, '可用模式:', Array.from(this.handlers.keys()))

    if (this.activeMode === mode) {
      // 相同模式，切换显示
      this.deactivateCurrentMode()
      return
    }

    // 停用当前模式
    this.deactivateCurrentMode()

    // 设置当前模式，但不自动激活任何handler
    const handlers = this.handlers.get(mode)
    if (handlers) {
      handlers.forEach(handler => {
        handler.setData(data)
        if (handler.auto()) {
          handler.display();
        }
      })
      this.activeMode = mode
      this.activeHandlers = handlers
      // 不再自动激活所有handler，让用户手动选择
      console.log(`已设置模式: ${mode}，等待用户手动激活handler`, handlers)
    } else {
      console.warn(`MapController: 未找到模式 ${mode} 的处理器`)
    }
  }

  deactivateCurrentMode(): void {
    if (this.activeMode) {
      this.activeHandlers.forEach(handler => handler.deactivate())
      this.activeMode = null
      this.activeHandlers = []
      console.log('停用当前模式')
    }
  }

  getActiveMode(): string | null {
    return this.activeMode
  }

  getActiveHandlers(): MapHandler[] {
    return this.activeHandlers
  }

  getHandlersForMode(mode: string): MapHandler[] {
    return this.handlers.get(mode) || []
  }

  hasMode(mode: string): boolean {
    return this.handlers.has(mode)
  }
}

// 单例实例
export const mapController = new MapController()